package com.link.play.fit.ai.ui.main.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.google.firebase.firestore.ListenerRegistration
import com.link.play.fit.ai.BuildConfig
import com.link.play.fit.ai.R
import com.link.play.fit.ai.RemoteConfig.vipNeedPlanPay
import com.link.play.fit.ai.RemoteConfig.vipProductCaloriePlan
import com.link.play.fit.ai.base.BaseFragment
import com.link.play.fit.ai.base.goToAc
import com.link.play.fit.ai.bean.CalControlData
import com.link.play.fit.ai.bean.CalControlReqData
import com.link.play.fit.ai.bean.ControlDayData
import com.link.play.fit.ai.bean.MealComponentsData
import com.link.play.fit.ai.bean.MealsData
import com.link.play.fit.ai.bean.UserGuide
import com.link.play.fit.ai.bean.WorkoutData
import com.link.play.fit.ai.databinding.ControlFgLayoutBinding
import com.link.play.fit.ai.databinding.ControlListItemBinding
import com.link.play.fit.ai.databinding.ControlListItemLayoutBinding
import com.link.play.fit.ai.databinding.ControlResultReclistItemBinding
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.kv.AuthCache.SUB_PRODUCT_TYPE
import com.link.play.fit.ai.kv.AuthCache.isVip
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.store.CloudStore.DOC_USER_GUIDE
import com.link.play.fit.ai.store.CloudStore.uid
import com.link.play.fit.ai.ui.main.MainAc
import com.link.play.fit.ai.ui.main.MainViewModel
import com.link.play.fit.ai.ui.main.adapter.HomeChildAdapter
import com.link.play.fit.ai.ui.main.fragment.control.ControlPage1Fg
import com.link.play.fit.ai.ui.main.fragment.control.ControlPage2Fg
import com.link.play.fit.ai.ui.main.fragment.control.ControlPage3Fg
import com.link.play.fit.ai.ui.main.fragment.control.ControlRefundAc
import com.link.play.fit.ai.ui.vip.VipFreeAc
import com.link.play.fit.ai.ui.vip.VipRenewAc
import com.link.play.fit.ai.ui.weightcontrol.ac.WeighControlMethodAc
import com.link.play.fit.ai.utils.CalendarUtils.calculateCyclePosition
import com.link.play.fit.ai.utils.CalendarUtils.calculateGroupIndex
import com.link.play.fit.ai.utils.CalendarUtils.calculateNewEndDate
import com.link.play.fit.ai.utils.CalendarUtils.checkExpiration
import com.link.play.fit.ai.utils.DateEx.getCurrentDayOfMonth
import com.link.play.fit.ai.utils.EventUtils
import com.link.play.fit.ai.utils.TimeUtils.calculateFinalTime
import com.link.play.fit.ai.utils.TimeUtils.completeControlDays
import com.link.play.fit.ai.utils.TimeUtils.convertTo24Hour
import com.link.play.fit.ai.utils.TimeUtils.getDateRange
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.util.UUID
import kotlin.math.abs


class ControlFg : BaseFragment<ControlFgLayoutBinding>(ControlFgLayoutBinding::inflate) {
    private val viewModel: MainViewModel by lazy { (requireActivity() as MainAc).viewModel }
    private var dateList: List<ControlDayData> = mutableListOf()

    companion object {
        var currentSelectedPosition = -1
    }

    private var currentPage = -1
    private var currentPagePosition = -1

    private lateinit var pagedList: List<List<ControlDayData>>
    private var registration: ListenerRegistration? = null
    private var dayNum = 0

    private val page1Fg by lazy(LazyThreadSafetyMode.NONE) {
        ControlPage1Fg()
    }
    private val page2Fg by lazy(LazyThreadSafetyMode.NONE) {
        ControlPage2Fg()
    }
    private val page3Fg by lazy(LazyThreadSafetyMode.NONE) {
        ControlPage3Fg()
    }
    private val exerciseAdapter by lazy(LazyThreadSafetyMode.NONE) {
        ExerciseListAdapter()
    }
    private val foodAdapter by lazy(LazyThreadSafetyMode.NONE) {
        FoodListAdapter()
    }
    private val fragmentList: List<Fragment> by lazy(LazyThreadSafetyMode.NONE) {
        mutableListOf(
            page1Fg,
            page2Fg,
            page3Fg
        )
    }
    private var currentMealsList: MutableList<MealsData> = mutableListOf()
    private var currentExerciseData: WorkoutData? = null
    private var calControlData: CalControlData? = null
    private var exerciseList: MutableList<WorkoutData> = mutableListOf()
    private var mealsList: MutableList<MutableList<MealsData>> = mutableListOf()
    private var calControlReqData: CalControlReqData? = null
    private var texts: MutableList<String> = mutableListOf()
    private var isFirstContent = true

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
//        if (vipNeedPlanPay) {
//            binding.itemLayout.neigouImg.setImageResource(R.mipmap.icon__home_neigou)
//        } else {
//            binding.itemLayout.neigouImg.setImageResource(R.mipmap.home_sub_img)
//        }
        initData()
        initListener()
        showData()
        obserLiveData()
        if (vipNeedPlanPay) {
            binding.itemLayout.neigouImg.setImageResource(R.mipmap.icon__home_neigou)
        } else {
            binding.itemLayout.neigouImg.setImageResource(R.mipmap.home_sub_img)
        }
    }

    private fun initData() = with(binding) {
        binding.zdLayout.homeImg.isVisible = false
        viewPager2.apply {
            offscreenPageLimit = 2
            adapter = HomeChildAdapter(childFragmentManager, lifecycle, fragmentList)
            registerOnPageChangeCallback(object :
                ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    updateDots(position % 3)
                }
            })
        }
        setupDots()

        itemLayout.exercistList.setLayoutManager(LinearLayoutManager(requireActivity()))
        itemLayout.exercistList.adapter = exerciseAdapter

        itemLayout.foodList.setLayoutManager(LinearLayoutManager(requireActivity()))
        itemLayout.foodList.adapter = foodAdapter

        texts.add(getString(R.string.the_waiting_time))
        texts.add(getString(R.string.the_long_loading))
        lifecycleScope.launch {
            while (true) {
                binding.itemLayout.theWaitingText.text = if (isFirstContent) texts[0] else texts[1]
                isFirstContent = !isFirstContent
                val delay = (3000 + (Math.random() * 2000)).toLong()
                delay(delay)
            }
        }
    }

    fun isShowNg(isShow: Boolean) {
        runCatching {
            "============= vipNeedPlanPay $vipNeedPlanPay it.isAppPurchaseVip $isShow".d()
            binding.itemLayout.neigouImg.isVisible = isShow
        }
    }

    private fun initListener() = with(binding) {
        binding.itemLayout.neigouImg.setOnClickListener {
            lifecycleScope.launch {
                val user = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
                user?.let {
                    if (vipNeedPlanPay) {
                        goToAc(VipRenewAc::class.java) {
                            putExtra("buyType", "controlFg")
                        }
                    } else {
                        goToAc(VipFreeAc::class.java)
                    }
                }
            }
        }
        itemLayout.modifyPlanText.setOnClickListener {
            EventUtils.event("Get_my_plan", value = "click")
            goToAc(WeighControlMethodAc::class.java)
        }
        lockText.setOnClickListener {
            EventUtils.event("Get_my_plan", value = "click")

            goToAc(WeighControlMethodAc::class.java)
        }
        itemLayout.txImg.setOnClickListener {
            itemLayout.resetText.isVisible = !itemLayout.resetText.isVisible
        }
        zdLayout.startLayout.setOnClickListener {
//            if (if(BuildConfig.DEBUG) false else vipNeedPlanPay) {
            if (vipNeedPlanPay) {
                goToAc(ControlRefundAc::class.java) {
                    putExtra("buyType", "controlFg")
                }
            } else {
                goToAc(VipFreeAc::class.java) {
                    putExtra("buyType", "controlFg")
                }
            }
        }
    }

    private var retry: Int = 3

    @SuppressLint("SetTextI18n")
    private fun obserLiveData() {
        viewModel.flushControlLiveData.observe(requireActivity(), {
            when (it) {
                "flushControl" -> {
                    lifecycleScope.launch {
                        val userGuide = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
                        userGuide?.let { it ->
                            binding.itemLayout.calValueText.text = it.caloriesDaily.toString()
                            binding.itemLayout.proteinValueText.text = it.proteinDaily.toString()
                            binding.itemLayout.fatValueText.text = it.fatsDaily.toString()
                            binding.itemLayout.carbsValueText.text = it.carbsDaily.toString()
                        }
                    }

                }
            }
        })

        lifecycleScope.launch {
            viewModel.foodBeanLiveData.collect { bean ->
                if (bean.status == -1) return@collect
                if (bean.calControlData == null) {
                    if (retry > 0) {
                        retry -= 1
                        calControlReqData?.let {
                            viewModel.getCalControl(it)
                        }
                    }
                    "retry  $retry obserLiveData".d()
                }
                bean.let { data ->
//                    "response bean  $data".d()

                    calControlData = data.calControlData
                    exerciseList.clear()
                    mealsList.clear()
                    calControlData?.dailyPlans?.forEachIndexed { index, dailyPlans ->
                        dailyPlans.workout?.let { exerciseList.add(it) }
                        mealsList.add(dailyPlans.meals)
                    }
                    if (exerciseList.isNotEmpty() || mealsList.isNotEmpty()) {
                        showLayout()
                    }
                    "exerciseList ${exerciseList.size}  ${exerciseList}".d()
                    "mealsList ${mealsList.size}  ${mealsList}".d()

                    setData(currentPage, currentPagePosition)
                }
            }
        }
    }

    private fun showLayout() = with(binding) {
        itemLayout.loadLayout.isVisible = false
        itemLayout.foodList.isVisible = true
        itemLayout.motionLayout.isVisible = true
        itemLayout.motionListLayout.isVisible = true
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setData(position: Int, index: Int) = with(binding) {
        "position $position  currentPage $currentPage".d()
        if (exerciseList.isEmpty() || mealsList.isEmpty()) return@with
        kotlin.runCatching {
            if (position == currentPage) {
                currentExerciseData = exerciseList[index]
                currentMealsList = mealsList[index]
                currentExerciseData?.let {
                    itemLayout.motionCalText.text = buildString {
                        append(it.totalCaloriesBurned.toInt())
                        append("kcal")
                    }
                    itemLayout.exerciseText.text = it.exerciseType
                }
            } else {
                currentPage = position
                calControlReqData?.apply {
                    cycle = position.toString()
                }
                viewModel.getCalControl(calControlReqData!!)
            }
        }
        foodAdapter.notifyDataSetChanged()
        exerciseAdapter.notifyDataSetChanged()
    }

    @SuppressLint("SetTextI18n")
    fun showData() = with(binding) {
        lifecycleScope.launch {
            val userGuide = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
            "userGuide  $userGuide".d()
            "vipNeedPlanPay ========== $vipNeedPlanPay ==============".d()
            userGuide?.let {
//                dayNum = (((abs(it.goalWeightKg - it.weightKg) / it.perWeightKg * 7).toInt()))
                dayNum = if (it.imperialMetric) {
                    (abs(it.goalWeightKg - it.weightKg) / it.perWeightKg * 7).toInt()
                } else {
                    (abs(it.goalWeightLbs - it.weightLbs) / it.perWeightLbs * 7).toInt()
                }
                if (dayNum == 0) {
                    dayNum = 30
                }
                var endTime: String
                if (vipNeedPlanPay) {
                    if (checkExpiration(it.planProductEndTime)) { //内购商品过期
                        CloudStore.set(DOC_USER_GUIDE, userGuide.apply { isAppPurchaseVip = false })
                    }
                    endTime = it.planProductEndTime
                } else {
                    endTime = if (isVip) {
                        calculateNewEndDate(it.planStartTime, it.subEndTime, SUB_PRODUCT_TYPE)
                    } else {
                        it.subEndTime
                    }
                }

                endTime = endTime.ifEmpty { getCurrentDayOfMonth() }
//                dateList = completeControlDays(getDateRange("2025-04-18", endTime, dayNum))
                dateList = completeControlDays(getDateRange(it.planStartTime, endTime, dayNum))
                pagedList = dateList.chunked(7)
                currentSelectedPosition =
                    dateList.indexOfFirst { it.timeDay == getCurrentDayOfMonth() }
                "planStartTime ${it.planStartTime}   endTime $endTime currentSelectedPosition  $currentSelectedPosition".d()

                val (pageIndex, pagePosition) = calculateCyclePosition(it.planStartTime, endTime)
//                val (pageIndex, pagePosition) = calculateCyclePosition("2025-04-18", endTime)

                currentPage = pageIndex.toInt()
                currentPagePosition = pagePosition.toInt()
                "currentPage $currentPage  currentPagePosition $currentPagePosition".d()

                showResultLayout(it)

                if (it.haveWeighControlPlan) { //健身计划

                    calControlReqData = CalControlReqData().apply {
                        userId = uid
                        planId = it.planId
                        cycle = "$currentPage"
                        height = it.heightCm.toString()
                        gender = it.gender.toString()
                        birth = "${it.bornYear}-${it.bornMonth}-${it.bornDay}"
                        type = it.goal
                        currentWeight = it.weightKg
                        goalWeight = it.goalWeightKg
                        weightLossGoal = abs(it.weightKg - it.goalWeightKg)
                        weightLossCycle = dayNum.toString()
                        customCalories = it.caloriesDaily.toString()
                        customProtein = it.proteinDaily.toString()
                        customCarbs = it.carbsDaily.toString()
                        customFat = it.fatsDaily.toString()
                    }
                    //5e9e6e1f-5432-44d2-8c6d-717670afc21e
                    if (it.planStartTime.isNotEmpty()) {
                        if (it.planId.isEmpty()) {
                            it.planId = UUID.randomUUID().toString()
                            CloudStore.set(
                                DOC_USER_GUIDE, it
                            )
                        }
                        calControlReqData?.apply {
                            planId = it.planId
                        }
                        viewModel.getCalControl(calControlReqData!!)
                    }

                    itemLayout.calValueText.text = it.caloriesDaily.toString()
                    itemLayout.proteinValueText.text = it.proteinDaily.toString()
                    itemLayout.fatValueText.text = it.fatsDaily.toString()
                    itemLayout.carbsValueText.text = it.carbsDaily.toString()

                    val weighControlMethod = it.weighControlMethod
                    if (weighControlMethod == 0) { //间接性断食
                        binding.itemLayout.txImg.isVisible = true
                        binding.itemLayout.dayWeightText.text =
                            getString(R.string.day_weight_loss_plan, "$dayNum")
                        if (it.imperialMetric) {
                            val lossWeightkg = abs(it.goalWeightKg - it.weightKg)
                            binding.itemLayout.lossGoalText.text =
                                getString(R.string.weight_loss_goal, lossWeightkg.toString())
                        } else {
                            val lossWeightLb = abs(it.goalWeightLbs - it.weightLbs)
                            binding.itemLayout.lossGoalText.text =
                                getString(R.string.weight_loss_goal_lbs, lossWeightLb.toString())
                        }

                        var fastStr = ""
                        val fastingGoal = it.fastingGoal
                        when (fastingGoal) {
                            0 -> {
                                binding.itemLayout.resetText.text =
                                    getString(R.string.fasting_goal_text, "12+12")
                                fastStr = "+12"
                            }

                            1 -> {
                                binding.itemLayout.resetText.text =
                                    getString(R.string.fasting_goal_text, "14+10")
                                fastStr = "+10"
                            }

                            2 -> {
                                binding.itemLayout.resetText.text =
                                    getString(R.string.fasting_goal_text, "16+8")
                                fastStr = "+8"
                            }
                        }
//                    val fastingStartTime = it.fastingStartTime

//                    binding.itemLayout.fastingText.text =
//                        getString(R.string.fasting_time, "(${fastingStartTime}-${fastStr})")
                        val endFastTime = calculateFinalTime(it.fastingStartTime, fastStr)
                        "fastingStartTime ${it.fastingStartTime}  endFastTime $endFastTime".d()
                        itemLayout.fastingText.text =
                            getString(
                                R.string.fasting_time,
                                "(${convertTo24Hour(it.fastingStartTime)}-${
                                    convertTo24Hour(
                                        endFastTime
                                    )
                                })"
                            )
                    } else { //卡路里控制
                        binding.itemLayout.txImg.isVisible = false
                        binding.itemLayout.resetText.isVisible = false

                        binding.itemLayout.dayWeightText.text =
                            getString(R.string.day_weight_training_plan, "$dayNum")
                        binding.itemLayout.fastingText.text =
                            getString(R.string.calorie_control)
                        val goal = it.goal

                        when (goal) { //0 gain ; 1 maintain ; 2 lose
                            0 -> {
                                if (it.imperialMetric) {
                                    val weightkg = abs(it.goalWeightKg - it.weightKg)
                                    binding.itemLayout.lossGoalText.text =
                                        getString(R.string.weight_gain_target_2, "$weightkg")
                                } else {
                                    val weightLbs = abs(it.goalWeightLbs - it.weightLbs)
                                    binding.itemLayout.lossGoalText.text =
                                        getString(R.string.weight_gain_target_2_lb, "$weightLbs")
                                }

                            }

                            1 -> {
                                binding.itemLayout.lossGoalText.text =
                                    getString(R.string.keep_weight)
                            }

                            2 -> {
                                if (it.imperialMetric) {
                                    val weightkg = abs(it.goalWeightKg - it.weightKg)
                                    binding.itemLayout.lossGoalText.text =
                                        getString(R.string.weight_loss_goal, "$weightkg")
                                } else {
                                    val weightLb = abs(it.goalWeightLbs - it.weightLbs)
                                    binding.itemLayout.lossGoalText.text =
                                        getString(R.string.weight_loss_goal_lb, "$weightLb")
                                }

                            }
                        }
                    }

                    "planStartTime ${it.planStartTime}  subEndTime ${it.subEndTime}  vipNeedPlanPay $vipNeedPlanPay".d()

//                        itemLayout.fgViewPager2.apply {
//                            adapter = DayPagerAdapter(dateList, { position ->
//                                "dateList  ${dateList[position].timeValue} ${dateList[position].timeDay}".d()
//                            })
//                            offscreenPageLimit = 2
//                            setPageTransformer { page, position ->
//                                page.translationX = position * page.width * 0.3f
//                            }
//                            currentItem = (dateList.size - 1) / 7 + 1
//                        }
                    setupRecyclerView()

                    binding.itemLayout.recyclerView.scrollToPosition(currentPage - 1)
                }
            }
        }

    }

    private fun showResultLayout(userGuide: UserGuide) {
        userGuide.let {
            if (vipNeedPlanPay) { //如果是第三套方案
                "vipNeedPlanPay $vipNeedPlanPay isAppPurchaseVip ${it.isAppPurchaseVip} haveWeighControlPlan ${it.haveWeighControlPlan} planStartTime ${it.planStartTime}".d()

                if (it.isAppPurchaseVip) {
                    if (it.haveWeighControlPlan) {
                        if (it.planStartTime.isEmpty()) {
                            binding.noneLayout.isVisible = true
                            binding.resultLayout.isVisible = false
                            binding.zdLayout.root.isVisible = false
                        } else {
                            binding.noneLayout.isVisible = false
                            binding.resultLayout.isVisible = true
                            binding.zdLayout.root.isVisible = false
                        }
                    } else {
                        binding.noneLayout.isVisible = true
                        binding.resultLayout.isVisible = false
                    }
                } else {
                    if (it.haveWeighControlPlan) {
                        binding.noneLayout.isVisible = false
                        binding.resultLayout.isVisible = false
                        binding.zdLayout.root.isVisible = true
                    } else {
                        binding.noneLayout.isVisible = true
                        binding.resultLayout.isVisible = false
                        binding.zdLayout.root.isVisible = false
                    }
                }
            } else {
                "isVip $isVip haveWeighControlPlan ${it.haveWeighControlPlan} it.planStartTime ${it.planStartTime}".d()
                if (isVip) {
                    if (it.haveWeighControlPlan) {
                        if (it.planStartTime.isEmpty()) {
                            binding.noneLayout.isVisible = false
                            binding.resultLayout.isVisible = false
                            binding.zdLayout.root.isVisible = true
                        } else {
                            binding.noneLayout.isVisible = false
                            binding.resultLayout.isVisible = true
                            binding.zdLayout.root.isVisible = false
                        }
                    }
                } else {
                    if (it.haveWeighControlPlan) {
                        binding.noneLayout.isVisible = false
                        binding.resultLayout.isVisible = false
                        binding.zdLayout.root.isVisible = true
                    } else {
                        binding.noneLayout.isVisible = true
                        binding.resultLayout.isVisible = false
                        binding.zdLayout.root.isVisible = false
                    }
                }
            }
        }
    }

//    private fun showResultLayout(userGuide: UserGuide) = with(binding) {
//            // 先重置所有布局状态
//            noneLayout.isVisible = false
//            resultLayout.isVisible = false
//            zdLayout.root.isVisible = false
//
//            val showZD = userGuide.haveWeighControlPlan && !isVip
//            val showNone = when {
//                vipNeedPlanPay -> handleVipPlanCase(userGuide)
//                else -> handleNormalVipCase(userGuide)
//            }
//            "isAppPurchaseVip ${userGuide.isAppPurchaseVip} showNone $showNone".d()
//            // 设置最终可见性
//            noneLayout.isVisible = showNone
//            resultLayout.isVisible = !showNone && !showZD
//            zdLayout.root.isVisible = showZD
//    }
//    // 处理第三套方案逻辑
//    private fun handleVipPlanCase(userGuide: UserGuide): Boolean {
//        return if (userGuide.isAppPurchaseVip) {
//            !userGuide.haveWeighControlPlan || userGuide.planStartTime.isEmpty()
//        } else {
//            !userGuide.haveWeighControlPlan
//        }
//    }
//
//    // 处理普通VIP逻辑
//    private fun handleNormalVipCase(userGuide: UserGuide): Boolean {
//        "isVip $isVip haveWeighControlPlan ${userGuide.haveWeighControlPlan} planStartTime ${userGuide.planStartTime}".d()
//        return if (isVip) {
//            !userGuide.haveWeighControlPlan || userGuide.planStartTime.isEmpty()
//        } else {
//            !userGuide.haveWeighControlPlan
//        }
//    }


    private fun setupRecyclerView() {
        binding.itemLayout.recyclerView.apply {
            layoutManager = LinearLayoutManager(
                requireActivity(),
                LinearLayoutManager.HORIZONTAL,
                false
            )
            adapter = PagerAdapter(pagedList, requireActivity()) { globalPos, position ->
                handleItemSelection(globalPos)
                val page = calculateGroupIndex(globalPos)

//                "page  $page  currentPage ${currentPage} ${dateList[globalPos].timeDay} globalPos $globalPos ${globalPos / 6} position $position".d()
                setData(page, position)
            }
            binding.itemLayout.recyclerView.onFlingListener = null
            // 添加分页吸附效果
            PagerSnapHelper().attachToRecyclerView(this)
        }

    }

    private fun handleItemSelection(globalPos: Int) {
        val prevSelected = currentSelectedPosition
        currentSelectedPosition = if (currentSelectedPosition == globalPos) -1 else globalPos
        refreshAffectedItems(prevSelected, currentSelectedPosition)
    }

    /**
     * 局部刷新新旧选中项
     */
    private fun refreshAffectedItems(oldPos: Int, newPos: Int) {
        listOf(oldPos, newPos).forEach { globalPos ->
            if (globalPos != -1) {
                val pageIndex = globalPos / 7 // 计算所在页
                val innerPos = globalPos % 7 // 计算页内位置
                // 局部刷新目标项
                (binding.itemLayout.recyclerView.findViewHolderForAdapterPosition(pageIndex)
                        as? PagerAdapter.PageViewHolder)?.let {
                    it.innerRecyclerView.adapter?.notifyItemChanged(innerPos)
                }
                binding.itemLayout.recyclerView.adapter?.notifyItemChanged(pageIndex)
            }
        }
    }

    private fun setupDots() {
        val dots = arrayOfNulls<ImageView>(3)
        binding.dotsContainer.removeAllViews()
        for (i in 0 until 3) {
            dots[i] = ImageView(activity).apply {
                setImageResource(R.drawable.dot_control_unselected)
                layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                ).apply {
                    setMargins(10, 0, 10, 0)
                }
            }
            binding.dotsContainer.addView(dots[i])
        }
        // 默认选中第一个圆点
        if (dots.isNotEmpty()) {
            dots[0]?.setImageResource(R.drawable.dot_control_selected)
        }
    }

    private fun updateDots(position: Int) {
        for (i in 0 until binding.dotsContainer.childCount) {
            val dot = binding.dotsContainer.getChildAt(i) as ImageView
            dot.setImageResource(
                if (i == position) R.drawable.dot_control_selected else R.drawable.dot_control_unselected
            )
        }
    }

    /**
     * 运动
     */
    inner class ExerciseListAdapter : RecyclerView.Adapter<ExerciseListAdapter.OneViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OneViewHolder {
            return OneViewHolder(
                layoutInflater.inflate(
                    R.layout.control_list_item,
                    parent,
                    false
                )
            )
        }

        @SuppressLint("NewApi")
        override fun onBindViewHolder(holder: OneViewHolder, position: Int) {
            val data = currentExerciseData?.exercises?.get(position)
            kotlin.runCatching {
                data?.let {
                    holder.itemBinding.nameText.text = buildString {
                        append(it.exerciseName)
                        append(it.duration)
                    }
                }

            }
        }

        override fun getItemCount(): Int {
            return currentExerciseData?.exercises?.size ?: 0
        }

        inner class OneViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var itemBinding: ControlListItemBinding =
                ControlListItemBinding.bind(itemView)
        }
    }

    /**
     * 食物list
     */
    inner class FoodListAdapter : RecyclerView.Adapter<FoodListAdapter.OneViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OneViewHolder {
            return OneViewHolder(
                layoutInflater.inflate(
                    R.layout.control_result_reclist_item,
                    parent,
                    false
                )
            )
        }

        @SuppressLint("NewApi", "SetTextI18n")
        override fun onBindViewHolder(holder: OneViewHolder, position: Int) {
            holder.itemBinding.foodText.text = currentMealsList[position].mealName
            if (currentMealsList[position].mealTotalCalories.toDouble() > 0) {
                holder.itemBinding.foodCalText.isVisible = true
                holder.itemBinding.foodCalImg.isVisible = true
                holder.itemBinding.foodCalText.text =
                    "${currentMealsList[position].mealTotalCalories.toDouble().toInt()}kcal"
            } else {
                holder.itemBinding.foodCalText.isVisible = false
                holder.itemBinding.foodCalImg.isVisible = false
            }

            holder.itemBinding.list.setLayoutManager(LinearLayoutManager(requireActivity()))
            holder.itemBinding.list.adapter =
                FoodListItemAdapter(currentMealsList[position].mealComponents)

        }

        override fun getItemCount(): Int {
            return currentMealsList.size
        }

        inner class OneViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var itemBinding: ControlResultReclistItemBinding =
                ControlResultReclistItemBinding.bind(itemView)
        }
    }

    /**
     * 食物item
     */
    inner class FoodListItemAdapter(val data: List<MealComponentsData>) :
        RecyclerView.Adapter<FoodListItemAdapter.OneViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OneViewHolder {
            return OneViewHolder(
                layoutInflater.inflate(
                    R.layout.control_list_item,
                    parent,
                    false
                )
            )
        }

        @SuppressLint("NewApi")
        override fun onBindViewHolder(holder: OneViewHolder, position: Int) {
            kotlin.runCatching {
                holder.itemBinding.nameText.text =
                    buildString {
                        append(data[position].mealComponentName)
                        append(data[position].mealComponentDesc)
                    }
            }
        }

        override fun getItemCount(): Int {
            return data.size
        }

        inner class OneViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var itemBinding: ControlListItemBinding =
                ControlListItemBinding.bind(itemView)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        registration?.remove()

    }

    class PagerAdapter(
        private val pages: List<List<ControlDayData>>,
        private val context: Context,
        private val onItemClick: (Int, Int) -> Unit
    ) : RecyclerView.Adapter<PagerAdapter.PageViewHolder>() {

        inner class PageViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val innerRecyclerView: RecyclerView = view.findViewById(R.id.pageRecyclerView)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PageViewHolder {
            return PageViewHolder(
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.control_item_page_container, parent, false)
            )
        }

        override fun onBindViewHolder(holder: PageViewHolder, pageIndex: Int) {
            holder.innerRecyclerView.apply {
                layoutManager = GridLayoutManager(context, 7) // 2列布局
                adapter = InnerAdapter(pages[pageIndex], pageIndex, context, onItemClick)
            }
        }

        override fun getItemCount() = pages.size
    }

    class InnerAdapter(
        private val items: List<ControlDayData>,
        private val pageIndex: Int,
        private val context: Context,
        private val onGlobalClick: (Int, Int) -> Unit
    ) : RecyclerView.Adapter<InnerAdapter.ItemViewHolder>() {
        var mPosition = -1

        inner class ItemViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            var itemBinding: ControlListItemLayoutBinding =
                ControlListItemLayoutBinding.bind(itemView)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
            return ItemViewHolder(
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.control_list_item_layout, parent, false)
            )
        }

        override fun onBindViewHolder(holder: ItemViewHolder, innerPos: Int) {
            val globalPos = pageIndex * 7 + innerPos
            holder.itemBinding.itemNameText.text = items[innerPos].timeValue
            if (items[innerPos].isAfter) {
                holder.itemBinding.itemNameText.setTextColor(context.getColor(R.color.color_69))
            } else {
                holder.itemBinding.itemNameText.isSelected = (globalPos == currentSelectedPosition)

            }
//            holder.itemView.apply {
//                isSelected = (globalPos == currentSelectedPosition)
//                setOnClickListener { onGlobalClick(globalPos) }
//            }
//            holder.itemBinding.itemNameText.isSelected =  (globalPos == currentSelectedPosition)

            holder.itemBinding.itemNameText.setOnClickListener {
                if (items[innerPos].isAfter) return@setOnClickListener
                if (globalPos == currentSelectedPosition) return@setOnClickListener
                mPosition = innerPos
                onGlobalClick(globalPos, innerPos)
            }
        }

        override fun getItemCount() = items.size
    }

}